package com.captjack.shiro.component;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import java.io.Serializable;

/**
 * @author Capt Jack
 * @date 2018/6/7
 */
@Component(value = "redisSessionManager")
public class CustomizeSessionManager extends DefaultWebSessionManager {

    /**
     * 自定义session管理
     */
    private final CustomizeSessionDaoImpl customizeSessionDaoImpl;

    @Override
    public void setSessionDAO(SessionDAO sessionDAO) {
        super.setSessionDAO(customizeSessionDaoImpl);
    }

    /**
     * 获取session
     * 优化单次请求需要多次访问redis的问题
     *
     * @param sessionKey sessionKey
     * @return session
     * @throws UnknownSessionException 异常
     */
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);
        ServletRequest request = null;
        if (sessionKey instanceof WebSessionKey) {
            request = ((WebSessionKey) sessionKey).getServletRequest();
        }
        if (request != null && null != sessionId) {
            Object sessionObj = request.getAttribute(sessionId.toString());
            if (sessionObj != null) {
                return (Session) sessionObj;
            }
        }
        Session session = super.retrieveSession(sessionKey);
        if (request != null && null != sessionId) {
            request.setAttribute(sessionId.toString(), session);
        }
        return session;
    }

    @Override
    public void setCacheManager(CacheManager cacheManager) {
        super.setCacheManager(cacheManager);
    }

    @Autowired
    public CustomizeSessionManager(CustomizeSessionDaoImpl customizeSessionDaoImpl) {
        super();
        this.customizeSessionDaoImpl = customizeSessionDaoImpl;
        setSessionDAO(null);
    }

}
